import { defineComponent } from 'vue';
import { getAchieve, performanceDetail } from '@/api/home';
import SheltV2 from '../../common/SheltV2';
import Echarts from '@/components/Echarts';
import './index.less';
import SearchRow from '../SearchRow';
import Detail from '../Detail';
import { ActionSheet, Button } from 'vant';

export default defineComponent({
  name: 'GroupPerformance',
  props: ['column'],
  setup(props) {
    const datas = ref({}) as AnyObject;
    const detailRef = ref();
    const personHander = reactive({
      show: false,
      selectedName: [],
      showName: '人员选择',
      list: []
    }) as AnyObject;
    const isPersonal = props.column?.includes('4');
    const data = reactive({
      search: {
        type: 1,
        year: undefined,
        is_team: isPersonal ? 0 : 1
      },
      list: [
        {
          key: 'year',
          type: 'popup_year',
          title: '日期选择',
          icon: 'calendar',
          placeholder: '请选择'
        }
      ],
      tab: {
        key: 'type',
        list: [
          { label: '月度目标', value: 1 },
          { label: '季度目标', value: 2 },
          { label: '年度目标', value: 3 }
        ]
      }
    }) as AnyObject;
    const detailData = ref({}) as AnyObject;
    const option = ref({
      color: ['#5470C6', '#EE6666'],
      tooltip: {
        trigger: 'axis'
      },

      legend: {
        icon: 'circle',
        itemGap: 20,
        left: 0,
        itemWidth: 10
      },
      grid: {
        left: 8,
        right:0,
        bottom: 20
      },
      xAxis: [
        {
          boundaryGap: false,
          type: 'category',
          axisTick: {
            show: false
          },

          axisLine: {
            // onZero: false,
            show: false,
            lineStyle: {
              color: '#666'
            }
          },
          data: []
        },
        {
          boundaryGap: false,
          show: false,
          data: []
        }
      ],
      yAxis: [
        {
          type: 'value',
          splitLine: {
            lineStyle: { type: 'dashed' },
            axisPointer: { show: false }
          }
        }
      ],
      series: [
        {
          areaStyle: {},
          name: '实际业绩',
          type: 'line',
          xAxisIndex: 1,
          smooth: true,
          data: [
            2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3
          ],
          symbol: 'none'
        },
        {
          symbol: 'none',
          areaStyle: {},
          name: '目标业绩',
          type: 'line',
          smooth: true,
          data: [
            3.9, 5.9, 11.1, 18.7, 48.3, 69.2, 231.6, 46.6, 55.4, 18.4, 10.3, 0.7
          ]
        }
      ]
    }) as any;

    const detailSlots = ref({
      fill: () => (
        <div class="flex-start">
          {!isPersonal && (
            <Button style={{height:"30px",marginRight:"10px"}} size="small" onClick={() => (personHander.show = true)}>
              {personHander.showName}
            </Button>
          )}
          <SearchRow onSearch={getAchieveData} data={data} />
        </div>
      )
    });

    getAchieveData();
    function getAchieveData() {
      const year = data.search.year ? data.search.year[0] : undefined;
      getAchieve({
        ...data.search,
        year,
        team_name: personHander.selectedName.join(",")
      }).then((res: AnyObject) => {
        isPersonal
          ? (datas.value = {
              performance: res.data.personal,
              table: res.data.personal_table
            })
          : (datas.value = {
              name: res.data.team_name,
              performance: res.data.team,
              table: res.data.team_table
            });
        option.value.xAxis[0].data = datas.value.table.month;
        option.value.xAxis[1].data = datas.value.table.month;
        option.value.series[0].data = datas.value.table.finish;
        option.value.series[1].data = datas.value.table.target;
        console.log(datas.value);
      });
    }

    const getDetailData = () => {
      console.log(detailData.value.year);
      detailData.value.team_name = personHander.selectedName.join(",");
      detailData.value.year =
        typeof detailData.value.year == 'string'
          ? detailData.value.year
          : detailData.value.year?.[0];
      performanceDetail(detailData.value).then((res) => {
        personHander.list = res.data;
      });
    };
    const viewDetail = () => {
      detailRef.value.show = true;
      detailData.value = data.search;
      getDetailData();
    };
    const handleSearch = () => {
      if (personHander.selectedName.length == datas.value.name.length) {
        personHander.showName = '全选';
      } else if (personHander.selectedName.length == 1) {
        personHander.showName = personHander.selectedName[0];
      } else if (personHander.selectedName.length > 1) {
        personHander.showName = personHander.selectedName[0] + '+';
      } else {
        personHander.showName = '人员选择';
      }
      detailRef.value.show?getDetailData(): getAchieveData();
      personHander.show = false;
    };
    const selectName = (name: string) => {
      const findIndex = personHander.selectedName.findIndex(
        (_name: string) => _name == name
      );
      findIndex >= 0
        ? personHander.selectedName.splice(findIndex, 1)
        : personHander.selectedName.push(name);
    };
    const selectAll = (status: boolean) => {
      if (status) {
        personHander.selectedName = datas.value.name;
      } else {
        personHander.selectedName = [];
      }
    };
    const seach = (val: any) => {
      Object.assign(detailData.value, val);
      getDetailData();
    };
    const handleTab = (tab: string) => {
      detailData.value.type = tab;
      getDetailData();
    };
    const chiefByType = computed(() => {
      const arr = ['日', '月', '季', '年'];
      return arr[detailData.value.type];
    });

    return () => (
      <>
        <SheltV2
          title={isPersonal ? '我的业绩' : '团队业绩'}
          more="查看详情"
          question="<div><p>【该数据每日凌晨更新一次】</p><p>团队业绩数据来源于BI，展示本人领导的团队相关的月度、季度、年度的销售收入、销售目标、销售达成率。</p></div>"
          v-slots={detailSlots.value}
          onViewDetail={viewDetail}
        >
          <Echarts option={option.value} />
          <div class="return flex-start">
            <div class="return_item">
              <div class="title">月度已达成(万元)</div>
              <div class="num">{datas.value.performance?.month_finish}</div>
              <div class="fill">
                月度目标<br/>{datas.value.performance?.month_target}
              </div>
              <div class="fill">
                达成率{datas.value.performance?.month_rate}
              </div>
            </div>
            <div class="return_item">
              <div class="title">季度已达成(万元)</div>
              <div class="num">{datas.value.performance?.quarter_finish}</div>
              <div class="fill">
                季度目标<br/>{datas.value.performance?.quarter_target}
              </div>
              <div class="fill">
                达成率{datas.value.performance?.quarter_rate}
              </div>
            </div>
            <div class="return_item">
              <div class="title">年度已达成(万元)</div>
              <div class="num">{datas.value.performance?.year_finish}</div>
              <div class="fill">
                年度目标{datas.value.performance?.year_target}
              </div>
              <div class="fill">达成率{datas.value.performance?.year_rate}</div>
            </div>
          </div>
        </SheltV2>
        <ActionSheet
          close-on-click-overlay={false}
          v-model:show={personHander.show}
          title={isPersonal ? '我的业绩' : '团队业绩'}
          teleport="body"
        >
          <div class="sheet_content">
            <div class="sheet_item">
              <div>
                <Button onClick={() => selectAll(true)}>全选</Button>
                <Button onClick={() => selectAll(false)}>反选</Button>
              </div>
              <ul class="flex-start">
                {datas.value.name?.map((_name: any) => (
                  <li
                    onClick={() => selectName(_name)}
                    class={{
                      active: personHander.selectedName.includes(_name)
                    }}
                  >
                    {_name}
                  </li>
                ))}
              </ul>
            </div>
          </div>
          <Button class="sheet_btn" type="primary" onClick={handleSearch}>
            确定
          </Button>
        </ActionSheet>
        <Detail
          title={isPersonal ? '业绩目标' : '团队业绩目标'}
          ref={detailRef}
          onHandleTab={handleTab}
          onSearch={seach}
          filterDetail={data}
        >
          {!isPersonal && (
            <Button class="extral_btn" size="small" onClick={() => (personHander.show = true)}>
              {personHander.showName}
            </Button>
          )}
          <ul class="performance_list">
            {personHander.list.map((item: AnyObject) => (
              <li class="flex-between">
                <div>{item.name}</div>
                <div class="li_item">
                  <p class="title">{item.target}</p>
                  <p>{chiefByType.value}度目标（万元）</p>
                </div>
                <div class="li_item">
                  <p class="title">{item.finish}</p>
                  <p>{chiefByType.value}度目标（万元）</p>
                </div>
                <div class="li_item">
                  <p class="title">{item.rate}</p>
                  <p>{chiefByType.value}月度达成率</p>
                </div>
              </li>
            ))}
          </ul>
        </Detail>
      </>
    );
  }
});
